var left = document.getElementsByClassName('left')[0];
var addArticle = left.getElementsByClassName('add_article')[0];
var controlArticle = left.getElementsByClassName('control_article')[0];
var right = document.getElementsByClassName('right')[0];
var article = right.getElementsByClassName('article')[0];
var list = right.getElementsByClassName('list')[0];
var listUl = list.getElementsByClassName('list_ul')[0];

var inputTitle = article.getElementsByClassName('input_title')[0];
var inputClassify = article.getElementsByClassName('input_classify')[0];
var inputContent = article.getElementsByClassName('input_content')[0];
var inputSubmit = article.getElementsByClassName('input_submit')[0];
var goLast=document.getElementsByClassName('go-last')[0]

goLast.addEventListener('click',function(){
    location.href='/'
})

addArticle.addEventListener('click', function () {
    this.className = 'add_article active'
    controlArticle.className = 'control_article'
    article.style.zIndex = '100'
    list.style.zIndex = '0'
})

controlArticle.addEventListener('click', function () {
    this.className = 'control_article active'
    addArticle.className = 'add_article'
    list.style.zIndex = '100'
    article.style.zIndex = '0'
})

//填充全部文章
function renderAllArticleData(e) {
    listUl.innerHTML=''
    e = JSON.parse(e)
    e.forEach((item) => {
        var li = document.createElement('li')
        var buttton = document.createElement('button')
        var span = document.createElement('span')
        li.className = 'list_item'
        span.className = 'item_title'
        buttton.className = 'item_delete'
        buttton.innerText = '删除'
        span.innerText = item.title
        buttton.setAttribute('id', item._id)
        addlistener(buttton)
        li.appendChild(span)
        li.appendChild(buttton)
        listUl.appendChild(li)
    })
}
//给删除按钮添加监听器
function addlistener(e){
    var id=e.getAttribute('id')
    e.addEventListener('click',function(){
        myAjax('post','/admin/deleteArticle',{id:id}).then((data)=>{
            alert(data)
            getDate()
        })

    })
}
//给添加文章按钮添加监听器
inputSubmit.addEventListener('click',function(){
    var title=inputTitle.value
    var classify=inputClassify.value
    var content=inputContent.value
    myAjax('post','/admin/addArticle',{title,content,classify}).then((data)=>{
        alert(data)
        inputTitle.value=''
        inputClassify.value=''
        inputContent.value=''
        getDate()
    })
})

async function getDate() {
    var AllArticleData = await myAjax('get', '/admin/getAllArticle', null)
    renderAllArticleData(AllArticleData)
}

getDate()